
import http from "../../utils/http_promise.js";
import WxValidate from '../../utils/WxValidate.js';

let app = getApp();
let baseUrl = app.globalData.baseUrl;

// pages/house/create.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
     imgArr:[],       // 已有图片展示;
     selArr:[],       // 新选择图片;
     uploadedImgs:[], // 已上传图片;
     index:0,
     form:{
        title:"",
        des:"",
        tel:"",
        imgs:[]
     },
     header:{}
  },

  del(e){

    let index = e.currentTarget.dataset.index; 
    let id = this.data.form.id; 

    http.request({
       url:'/house/delimg',
       data:{index,id}
    })
    .then(res=>{

      if(res.data.status!=200) return wx.showToast({
        title: '删除失败!'
      })

      let tmpArr = [...this.data.form.imgs];
      tmpArr.splice(index,1);
      this.setData({
        imgArr: tmpArr
      })
      
    })
    
  },

  initValidate() {

    // 验证规则
    const rules = {
      title: {
        required: true,
        minlength: 5,
        maxlength: 25
      },
      des: {
        required: true,
        minlength: 5,
        maxlength: 300
      },
      tel: {
        required: true,
        tel: true
      }
    }
    
    // 提示信息
    const messages = {
      title: {
        required: "请输入房源标题!",
        minlength:"房源标题至少5位",
        maxlength:"房源标题不多于25位"
      },
      des: {
        required: "请输入房源详情!",
        minlength: "房源详情至少5位",
        maxlength: "房源详情不超过300位"
      },
      tel: {
        required: "请输入手机号码!",
        tel: "请输入正确手机号码"
      }
    }

    // 自定义验证规则
    this.WxValidate = new WxValidate(rules, messages);
  
  },
  
  chooseImage(){

    let that = this;

    // 选择图片api接口 
    wx.chooseImage({
      count: 3,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {

        let tmpArr = [...that.data.selArr];
        let selArr = tmpArr.concat(res.tempFilePaths);

        that.setData({
          selArr
        })

      }
    })


  },
  
  unSel(e){
    
     let idx = e.currentTarget.dataset.idx;
     let tmpArr = [...this.data.selArr];
     tmpArr.splice(idx,1);
     this.setData({
        selArr:tmpArr
     });
     console.log('unsel',idx);
    
  },
  
  onSubmit(e){

    let that = this;

    // 验证是否登录
    http.checkLogin();
    
    // 表单验证
    let params = e.detail.value;
    that.data.formData = e.detail.value; 

    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];
      wx.showModal({
        title: '提示信息',
        content:error.msg
      });
      return false
    }

    // 设置token
    let token = wx.getStorageSync("token");
    that.data.header.Authorization = 'Bearer ' + token;

    // 图片验证
    if(that.data.selArr.length != 0){
      // 上传文件
      that.uploadFile(that.data.selArr[that.data.index]); 
    }else{
       that.save();
    }

    
  },

  uploadFile(picPath){
    
    let that = this;
    // 2 上传文件;
    wx.uploadFile({

      url: baseUrl + "/house/upload",
      filePath: picPath,
      name: 'file',
      header:that.data.header,
      formData: {
        'index': that.data.index
      },

      success(res) {

        that.data.uploadedImgs.push(res.data);
        that.data.index++;
        if(that.data.index<that.data.selArr.length){
          that.uploadFile(that.data.selArr[that.data.index]);
        }else{
            //处理图片全部上传完成的业务逻辑
            console.log("success");
            Object.assign(that.data.formData,{'imgs':that.data.uploadedImgs});
            that.save();
        }
        
        
      }
    
    })
    
  },
  
  save(){

     // 3 保存表单数据 
     let that = this;
     that.data.formData.imgs = [...that.data.uploadedImgs];
      
      http.request({
        url:"/house/update",
        data:that.data.formData,
        requireAuth:true,
        method:"post",
        header:that.data.header
     })
     .then(res=>{
        console.log(res);
        if(res.data.status == "201"){
          wx.showToast({
            title: res.data.msg,
          })
          setTimeout(()=>{
             wx.navigateBack();
          },2000);
        }
     })
     
  },

  getDetail(id){

     //console.log(id);
    http.request({
    "url":"/house/detail",
      data:{id}
    })
    .then(res=>{
      
      this.setData({
        form:res.data,
        imgArr:res.data.imgs
      })

    })


  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    http.checkLogin();
    this.initValidate();
    this.getDetail(options.id);
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
     
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
  

})